#include "kb.h"
#include "statement.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct _subscriber {
	kb_subscriber sc;
	void* data;
	struct _subscriber* next;
};

typedef struct _subscriber subscriber;

struct _kb {
	subscriber* subscribers;
	const char* filename;
	Statement* facts;
};

KB* kb_new() {
	KB* result = (KB*)malloc(sizeof(KB));
	if ( !result )
		return NULL;
	result->subscribers = NULL;
	result->filename = NULL;
	result->facts = NULL;
}

const char[] filesig = { 'K', 'B', '0', '1'};

int _read_statement(FILE* f, Statement** list) {
	char* s, *p, *o;
	int op;
	if ( _read_string(f, &s) && _read_string(f, &p) && _read_string(f, &o)
			&& _read_int(f, &op) ) {
		Statement* new = stmt_new(s, p, o, op);
		if ( ! new )
			return 0;
		stmt_prepend(list, new);
	}
	return 1;
}

KB* kb_from_file(const char* filename) {
	KB* result = NULL;
	Statement* stmt;
	FILE* f = fopen(filename, "r");
	char buf[1024];
	if (!f) {
		fprintf(stderr, "Cannot open file %s\n", filename);
		return NULL;
	}
	if ( !fread(buf, 4, 1, f) ) {
		fprintf(stderr, "Signature cannot be read!\n");
		goto close;
	}
	if (strncmp(buf, filesig, 4) != 0 ) {
		fprintf(stderr, "Signature doesn't match!\n");
		goto close;
	}
	while ( _read_statement(f, &stmt) )  {} 


close:
	fclose(f);
	return result;
}

